package md.mru.frontend.controllers;

import md.mru.core.domains.type.OrderStateType;
import md.mru.core.dtos.*;
import md.mru.core.service.FolderService;
import md.mru.core.service.OrderService;
import md.mru.frontend.utils.FolderStateType;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author sergiu.marin
 * @since 29.03.2014
 */
@ManagedBean
@ViewScoped
public class FolderAdministrationBean extends BackingBean {

    private static final long serialVersionUID = 7353188633444187169L;
    private static final int ORDERS_SIZE = 10;

    @ManagedProperty(value = "#{folderService}")
    private FolderService folderService;

    @ManagedProperty(value = "#{orderService}")
    private OrderService orderService;

    @ManagedProperty(value = "#{authenticationBean}")
    private AuthenticationBean authenticationBean;

    @ManagedProperty(value = "#{imageAdministrationBean}")
    private ImageAdministrationBean imageAdministrationBean;
    /*@ManagedProperty(value = "#{treeAdministrationBean}")
    private TreeAdministrationBean treeAdministrationBean;*/
    private FolderDto selectedFolder;
    private List<FolderDto> folders;
    private List<OrderDto> orders = new ArrayList<>();
    private List<IssuerDto> issuers;
    private List<AdvancementRankDto> advancementRanks;
    private List<PublicFunctionDto> publicFunctions;
    private List<EffectiveDto> effectives;
    private long elementsNo;
    //private OrderDto selectedOrder;
    //private OrderStateType[] treeAvailableFolderStates = {OrderStateType.TRAINEE, OrderStateType.EMPLOYED};
    //private OrderStateType[] availableFolderStates;
    private List<OrderTypeDto> orderTypes;
    private List<OrderTypeGroupDto> orderTypeGroups;
    private boolean transferActivated;

    public void initializeFoldersContent() {
        this.folders = folderService.getUnAtachedFolders();
    }

    public String initListFolders() {
        this.folders = folderService.getFolders();
        return "list-folder";
    }

/*    public void initListUnAtachedFolders() {
        this.folders = folderService.getUnAtachedFolders();
    }*/

    public void resetCreateFolderDialog() {
        this.selectedFolder = null;
    }

    public String displayEvents() {
        this.selectedFolder = null;
        TreeAdministrationBean treeAdministrationBean = (TreeAdministrationBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("treeAdministrationBean");
        treeAdministrationBean.setAdministrationActivated(false);
        treeAdministrationBean.setSelectedGroupId(null);
        utilAdministrationBean.loadNextEvents();
        return "person-folder";
    }

    public String initCreateNewFolder() {
        this.selectedFolder = new FolderDto();
        return "new-folder";
    }

    /*public void initEmploymentOrderDialog() {
        this.selectedFolder = new FolderDto();
        this.selectedOrderTypeGroupId = OrderStateType.EMPLOYMENT.id;
        this.folders = this.folderService.loadFoldersByState(FolderStateType.NEW.folderStateId, FolderStateType.FIRED.folderStateId);
        this.getObjectMappingConverter().mapObjectList(folders);

        this.initDialogCommonComponetns();
    }*/

    /*public void initDialogCommonComponetns() {
        this.selectedOrder = new OrderDto();
        this.orderTypes = orderService.loadOrderTypesByGroup(FolderStateType.NEW.orderTypeGroupId);
        this.getObjectMappingConverter().mapObjectList(orderTypes);
        if (issuers == null) {
            issuers = orderService.loadIssuers();
            this.getObjectMappingConverter().mapObjectList(issuers);
        }
    }*/

    public boolean orderGroupDisabled() {
        return this.selectedFolder != null && this.selectedFolder.getFolderState() != null
                && this.selectedFolder.getFolderState().getId() == FolderStateType.DISCHARGED.folderStateId;
    }

    /*public void initFolderAttachDialog() {
        //this.selectedOrder = new OrderDto();
        this.selectedFolder = new FolderDto();
        *//*this.folders = this.folderService.loadFoldersByStates(EnumSet.of(OrderStateType.NEW, OrderStateType.VALIDATED,
                OrderStateType.TRANSFER, OrderStateType.TEMPORARILY_SUSPENDED));*//*
        this.folders = this.folderService.loadFoldersByState(FolderStateType.NEW.folderStateId, FolderStateType.FIRED.folderStateId);
        this.orderTypes = orderService.loadOrderTypesByGroup(FolderStateType.NEW.orderTypeGroupId);
        if (issuers == null) {
            issuers = orderService.loadActiveIssuers();
        }
        if (publicFunctions == null) {
            publicFunctions = orderService.getPublicFunctions();
        }
        if (advancementRanks == null) {
            advancementRanks = orderService.getAdvancementRanks();
        }
        if (effectives != null) {
            effectives = orderService.getEffectives();
        }

        this.getObjectMappingConverter().mapObjectList(folders);
        this.getObjectMappingConverter().mapObjectList(orderTypes);
    }*/

    /*public void onOrderGroupSelect(AjaxBehaviorEvent event) {
        OrderTypeGroupDto value = (OrderTypeGroupDto) ((UIOutput) event.getSource()).getValue();
        this.selectedOrderTypeGroupId = value.getId();
        this.orderTypes = orderService.loadOrderTypesByGroup(value.getId());
        getObjectMappingConverter().mapObjectList(orderTypes);
        this.selectedOrder = new OrderDto();
    }*/

    /*public void initCommonOrderDialog() {
        this.selectedOrder = new OrderDto();
        this.selectedFolder = new FolderDto();
        *//*this.folders = this.folderService.loadFoldersByStates(EnumSet.of(_OrderStateType.NEW, _OrderStateType.VALIDATED,
                OrderStateType.TRANSFER, _OrderStateType.TEMPORARILY_SUSPENDED));*//*
        this.getObjectMappingConverter().mapObjectList(folders);
    }*/

    /*public void confirmTransfer() {
        //this.selectedOrder = new OrderDto();
        this.orderTypes = orderService.loadOrderTypesByGroup(FolderStateType.TRANSFER.orderTypeGroupId);
        //this.availableFolderStates = new OrderStateType[]{OrderStateType.TRANSFER};
    }*/

    public void cancelTransfer() {
        this.transferActivated = false;
        //this.selectedFolder = null;
    }

    public void savePersonalInfo() {
        if (!selectedFolder.isEditable()) {
            folderService.save(selectedFolder);
        }
    }

    public void saveFolderData() {
        FolderStateDto folderState = folderService.getFolderState(FolderStateType.NEW.folderStateId);
        selectedFolder.setFolderState(folderState);
        selectedFolder.setId(folderService.save(selectedFolder));
        this.folders.add(selectedFolder);
    }

    /*public void createOrder() {
        this.selectedOrder.getFolders().add(selectedFolder);
        this.selectedOrder.setCreatedDate(Calendar.getInstance().getTime());
        this.selectedOrder.setId(this.orderService.saveOrder(this.selectedOrder));

        // add event
        TreeAdministrationBean treeAdministrationBean = (TreeAdministrationBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("treeAdministrationBean");
        String nodePath = this.buildBreadCrump(treeAdministrationBean.getSelectedTreeNode());
        utilAdministrationBean.createNewEvent(new EventDto(EventType.ORDER, nodePath, selectedOrder, authenticationBean.getLoginUser().getUser()));


        *//*if (!OrderStateType.NOT_GENERAL_STATES.contains(this.selectedOrder.getOrderStateType())) {
            this.selectedFolder.setGeneralState(this.selectedOrder.getOrderStateType());
        }
        if (this.selectedOrder.getOrderStateType().equals(OrderStateType.RETURN_TO_WORK)
                || this.selectedOrder.getOrderStateType().equals(OrderStateType.TRANSFER)) {
            this.selectedFolder.setCurrentState(OrderStateType.EMPLOYED);
        } else {
            this.selectedFolder.setCurrentState(this.selectedOrder.getOrderStateType());
        }
        this.folderService.save(selectedFolder.getId(), this.selectedFolder.getGeneralState(), this.selectedFolder.getCurrentState());*//*
        this.selectedFolder.setFolderState(selectedOrder.getOrderType().getFolderState());
        this.folderService.save(selectedFolder);
    }*/

    public void changeFolderState(OrderDto order) {
        this.selectedFolder.setFolderState(order.getOrderType().getFolderState());
        this.folderService.save(selectedFolder);
    }

    public String navigateToCreateFolder() {
        return "new-folder";
    }

    public String navigateToFolderList() {
        this.folders = folderService.getFolders();
        return "list-folder";
    }

    public FolderDto getSelectedFolder() {
        if (selectedFolder == null) {
            selectedFolder = new FolderDto();
        }
        return selectedFolder;
    }

    public void initFolderOrdersTab() {
        this.loadNextOrders();
    }

    public void loadNextOrders() {
        OrdersWrapper ordersWrapper = orderService.loadNextOrders(this.selectedFolder.getId(), orders.size(), ORDERS_SIZE);
        this.orders.addAll(ordersWrapper.getOrders());
        elementsNo = ordersWrapper.getTotalElements() - this.orders.size();
    }

    public void populateFolderPage(Long folderId) {
        selectedFolder = folderService.getFolder(folderId);
    }

    /*public void initOrderForm() {
//        this.orderTypes = this.selectedFolder.getCurrentState().availableFolderStates;
        this.orderTypes = orderService.loadOrderTypesByGroups(this.selectedFolder.getFolderState().getOrderTypeGroups());
        //this.orderTypes = this.selectedFolder.getCurrentState().availableFolderStates;
        this.selectedOrder = new OrderDto();
        //this.selectedFolder = null;
    }*/

    public void setSelectedFolder(FolderDto selectedFolder) {
        //    this.transferActivated = false;
        this.selectedFolder = selectedFolder;
    }

    public void showFolder(FolderDto selectedFolder) {
        this.selectedFolder = selectedFolder;
        this.initOrderTypeGroupComponent();
        this.setupFolderEmployedDate();
        this.imageAdministrationBean.loadFolderImage(selectedFolder.getId());
    }

    public void initOrderTypeGroupComponent() {
        this.orderTypeGroups = orderService.loadOrderTypeGroups(selectedFolder.getFolderState().getId());
        getObjectMappingConverter().mapObjectList(orderTypeGroups);
        this.transferActivated = false;
    }

    public void setupFolderEmployedDate() {
        Date employedDate = orderService.getFolderEmployedDate(selectedFolder.getId());
        this.selectedFolder.setEmployedDate(employedDate);
    }


    public void setFolderService(FolderService folderService) {
        this.folderService = folderService;
    }

    public OrderService getOrderService() {
        return orderService;
    }

    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    public List<FolderDto> getFolders() {
        return folders;
    }

    public List<OrderDto> getOrders() {
        return orders;
    }

    public long getElementsNo() {
        return elementsNo;
    }

    public void setElementsNo(long elementsNo) {
        this.elementsNo = elementsNo;
    }

    /*public OrderDto getSelectedOrder() {
        return selectedOrder;
    }

    public void setSelectedOrder(OrderDto selectedOrder) {
        this.selectedOrder = selectedOrder;
    }*/


    /*public OrderStateType[] getAvailableFolderStates() {
        return availableFolderStates;
    }*/

    // TODO - expose common orders
    public OrderStateType[] getEmployedFolderStates() {
        return null;//employedFolderStates;
    }

    /*public OrderStateType[] getFolderStates() {
        return folderStates;
    }*/

    /*public OrderStateType[] getTreeAvailableFolderStates() {
        return treeAvailableFolderStates;
    }*/

    public void setAuthenticationBean(AuthenticationBean authenticationBean) {
        this.authenticationBean = authenticationBean;
    }

    /*public boolean checkOrderType(OrderStateType type) {
        return selectedOrderTypeGroupId != null && type.id == selectedOrderTypeGroupId;
    }*/

    /*public boolean showMain() {
        return OrderStateType.ADVANCEMENT.id == selectedOrderTypeGroupId
                || OrderStateType.ATTESTATION.id == selectedOrderTypeGroupId;
    }

    public boolean showEmploymentDate() {
        return OrderStateType.EMPLOYMENT.id == selectedOrderTypeGroupId
                || OrderStateType.TRANSFER.id == selectedOrderTypeGroupId;
    }

    public boolean showEventDate() {
        return OrderStateType.EMPLOYMENT.id == selectedOrderTypeGroupId
                || OrderStateType.DISCHARGE.id == selectedOrderTypeGroupId
                || OrderStateType.SUSPENDED.id == selectedOrderTypeGroupId
                || OrderStateType.TRANSFER.id == selectedOrderTypeGroupId
                || OrderStateType.RECALL.id == selectedOrderTypeGroupId
                || OrderStateType.WORK_INCAPACITY.id == selectedOrderTypeGroupId;
    }

    public boolean showRangeDate() {
        return OrderStateType.HOLIDAY.id == selectedOrderTypeGroupId
                || OrderStateType.AWAY.id == selectedOrderTypeGroupId
                || OrderStateType.TRAINING.id == selectedOrderTypeGroupId
                || OrderStateType.WORK_INCAPACITY.id == selectedOrderTypeGroupId;
    }

    public boolean showToDate() {
        return OrderStateType.SUSPENDED.id == selectedOrderTypeGroupId
                || OrderStateType.HOLIDAY.id == selectedOrderTypeGroupId
                || OrderStateType.AWAY.id == selectedOrderTypeGroupId
                || OrderStateType.TRAINING.id == selectedOrderTypeGroupId
                || OrderStateType.WORK_INCAPACITY.id == selectedOrderTypeGroupId;
    }

    public boolean showNotes() {
        return OrderStateType.DISCHARGED.id == selectedOrderTypeGroupId
                || OrderStateType.SUSPENDED.id == selectedOrderTypeGroupId
                || OrderStateType.AWAY.id == selectedOrderTypeGroupId
                || OrderStateType.RESTORING.id == selectedOrderTypeGroupId
                || OrderStateType.RECALL.id == selectedOrderTypeGroupId
                || OrderStateType.HOLIDAY_SUPPLEMENT.id == selectedOrderTypeGroupId;
    }*/

    public boolean isTransferActivated() {
        return transferActivated;
    }

    public void setTransferActivated(boolean transferActivated) {
        this.transferActivated = transferActivated;
    }

    public List<OrderTypeDto> getOrderTypes() {
        return orderTypes;
    }

    public List<OrderTypeGroupDto> getOrderTypeGroups() {
        return orderTypeGroups;
    }

    public List<IssuerDto> getIssuers() {
        return issuers;
    }

    public List<PublicFunctionDto> getPublicFunctions() {
        return publicFunctions;
    }

    public List<AdvancementRankDto> getAdvancementRanks() {
        return advancementRanks;
    }

    public List<EffectiveDto> getEffectives() {
        return effectives;
    }

    public void setImageAdministrationBean(ImageAdministrationBean imageAdministrationBean) {
        this.imageAdministrationBean = imageAdministrationBean;
    }
}
